package com.itoffer.web;

import com.itoffer.pojo.ResumeBasicInfo;
import com.itoffer.service.ResumeService;
import com.itoffer.service.impl.ResumeServiceImpl;
import org.apache.ibatis.javassist.SerialVersionUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;

/**
 * 简历头像上传servlet
 */
@WebServlet("/resumePicUploadServlet")
@MultipartConfig
public class ResumePicUploadServlet extends HttpServlet {
    private ResumeService resumeService = new ResumeServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getContextPath();
        String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path ;

        // System.out.println("头像上传成功");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //获取文件上传域
        Part part = req.getPart("headShot");
        //System.out.println(part);
        //获取上传文件名称
        String fileName = part.getSubmittedFileName();
        //System.out.println(fileName);
        //防止上传文件重名，对文件进行重命名
        String newFileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
        //将上传的文件保存在服务器项目发布路径的applicant/images目录下


        String filePath = getServletContext().getRealPath("/applicant/images");
        //System.out.println("文件保存路径为:" + filePath);

        File f = new File(filePath);
        if (!f.exists())
            f.mkdirs();

        part.write(filePath + "/" + newFileName);
        //更新简历照片，操作数据库,此处模拟用编号为99的简历
        HttpSession session = req.getSession();
        ResumeBasicInfo basicInfo =(ResumeBasicInfo) session.getAttribute("basicInfo");
        resumeService.updatePicPath(basicInfo.getBasicinfo_id(), newFileName);
        //System.out.println("更新照片成功");
        //照片更新成功，回到我的简历界面
        String contextPath = req.getContextPath();
        resp.sendRedirect(contextPath + "/resume/selectCurrentResumeServlet");


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
